<?php

namespace apiend\modules\mall\models;

use Yii;

/**
 * 购物车商品列表
 * 
 * @author emhome<emhome@163.com>
 * @since 2.0
 */
class CartSearch extends \common\models\shop\ShopCart implements \common\db\SearchModelInterface {

    /**
     * 检索购物车中商品
     * @return \common\db\ActiveQuery
     */
    public function search() {
        $query = $this->buildQuery();
        $data = $query->all();
        $result = static::groupFormat($data);
        return array_values($result);
    }

    /**
     * 检索购物车中商品
     * @return \common\db\ActiveQuery
     */
    public function searchItem() {
        $query = $this->buildQuery();
        $query->andWhere(['t.product_id' => $this->product_id]);
        $data = $query->all();
        $result = static::groupFormat($data);
        return array_pop($result);
    }

    /**
     * 检索购物车中商品
     * @return \common\db\ActiveQuery
     */
    public function buildQuery() {
        $query = static::findActive('t')->andWhere([
            'and',
            ['>=', 't.status', static::STATUS_DEFAULT],
            ['t.user_id' => $this->user_id],
        ]);
        $query->innerJoinWith(['product', 'goods']);
        $query->orderBy([
            't.created_at' => SORT_DESC
        ]);
        return $query;
    }

    /**
     * @inheritdoc
     */
    public function fields() {
        return [
            'id',
            'sku' => 'skuName',
            'price',
            'market_price' => 'marketPrice',
            'stock',
            'num',
            'goods_id',
        ];
    }

}
